package com.fbms.common.utils;


import java.util.*;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 类描述：流的封装类
 *
 * @ClassName StreamKit
 * @Author HappyBoy
 * @Date 2023-03-08 15:41
 **/
public class StreamKit {


    public static <T> List<T> distinct(List<T> list){
        if (Objects.isNull(list) || list.isEmpty()) {
            return new ArrayList<>(0);
        }
        return list.stream().distinct().collect(Collectors.toList());
    }


    public static <T, R> List<R> mapToList(List<T> list, Function<T, R> func) {
        if (Objects.isNull(list) || list.isEmpty()) {
            return new ArrayList<>(0);
        }
        return list.stream()
                .map(func)
                .collect(Collectors.toList());
    }



    /**
     * 过滤
     * @param list 列表
     * @param predicate 断言
     * @return 列表
     * @param <T> 泛型
     */
    public static <T> List<T> filter(List<T> list, Predicate<? super T> predicate) {
        if (Objects.isNull(list) || list.isEmpty()) {
            return new ArrayList<>(0);
        }
        return list.stream().filter(predicate).collect(Collectors.toList());
    }

    public static <T,U extends Comparable<? super U>> List<T> filterAndSort(List<T> list, Predicate<? super T> predicate, Function<? super T, ? extends U> keyExtractor) {
        if (Objects.isNull(list) || list.isEmpty()) {
            return new ArrayList<>(0);
        }
        return list.stream().filter(predicate).sorted(Comparator.comparing(keyExtractor)).collect(Collectors.toList());
    }

    /**
     * 转换
     * @param fromList 原list
     * @param function 方法
     * @return 转换之后的list
     * @param <T> 类型T
     * @param <R> 类型R
     */
    public static <T, R> List<R> convertList(List<T> fromList, Function<T, R> function) {
        return fromList.stream().map(function).collect(Collectors.toList());
    }

}
